package com.android.pindaojia.fragment.group;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.pindaojia.activity.BaseObject;
import com.android.pindaojia.fragment.BaseLazyFragment;
import com.android.pindaojia.model.detail.BrandGoodsListTCascadeData;
import com.android.pindaojia.model.group.SeaAmoyListData;
import com.android.pindaojia.model.group.SeaAmoyListDataCallback;
import com.android.pindaojia.utils.ConstantsUrl;
import com.android.pindaojia.utils.HttpUtils;
import com.android.pindaojia.utils.ObjectUtils;
import com.android.pindaojia.view.MyGridView;
import com.android.pindaojia.view.group.VRefreshLayout;
import com.android.pindaojia.view.recycleview.CustomLoadMoreView;
import com.android.pindaojia.view.recycleview.CustomRecycleView;
import com.android.pindaojia.R;
import com.android.pindaojia.model.detail.BrandGoodsListTCascadeCallback;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/8/22.
 */

public class Fragment_SACountryTCList extends BaseLazyFragment implements BaseQuickAdapter.RequestLoadMoreListener {


    @BindView(R.id.main_top_bg)
    Toolbar mainTopBg;
    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    VRefreshLayout mRefreshLayout;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.progress_loading)
    FrameLayout progressLoading;
    private View rootView;
    private AdaptList adapter;
    private LayoutInflater inflater;
    private boolean networkConnected;
    private FragmentActivity mcontext;
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String id;
    private String country_id;
    private int page = 1;
    private View inflate;
    private TextView refresh_textView;
    private ArrayList<BrandGoodsListTCascadeData.DataBean.ListBean> listdata = new ArrayList<>();
    private ArrayList<SeaAmoyListData.DataBean.Cat_isrecBean> cat_isrec = new ArrayList<>();
    private ArrayList<SeaAmoyListData.DataBean.Cat_isrecBean> mList_HeadSort = new ArrayList<>();
    private StaggeredGridLayoutManager smLayoutManager;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            id = getArguments().getString(ARG_PARAM1);
            country_id=getArguments().getString(ARG_PARAM2);
        }
    }

    public static Fragment_SACountryTCList newInstance(String id,String country_id) {
        Fragment_SACountryTCList fragment= new Fragment_SACountryTCList();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1,id);
        args.putString(ARG_PARAM2,country_id);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected void initPrepare() {
        ReFreshData();
    }

    private void initRecycle() {
        adapter = new AdaptList(mcontext, null, "0");
        // adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, mRecyclerView);
        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.GetToTop((ImageView) rootView.findViewById(R.id.top), 0);

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getId(), "");
            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public boolean onItemChildClick(BaseQuickAdapter adapter1, View view, int position) {
                switch (view.getId()) {
                    case R.id.main_list_item_go_kai:
                        //   ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getId(), "");
                        break;
                }
                return false;
            }
        });
    }


    @Override
    protected void onInvisible() {

    }


    @Override
    protected void initData() {


        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        if (networkConnected) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            page=1;
            GetSAmoyTC();
            GetListData(page);
        } else {

            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }

    }


    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.inflater = inflater;
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        rootView = inflater.inflate(R.layout.layout_recycle_refresh, container, false);
        ButterKnife.bind(this, rootView);
        mcontext = getActivity();
        mainTopBg.setVisibility(View.GONE);
        initRecycle();
        return rootView;
    }


    private void initHeadSort() {
        mList_HeadSort.clear();
        if (cat_isrec == null ||cat_isrec.size() == 0) {
            return;
        }
        if (cat_isrec.size() >= 8) {
            for (int i = 0; i < cat_isrec.size(); i++) {
                mList_HeadSort.add(new SeaAmoyListData.DataBean.Cat_isrecBean(cat_isrec.get(i).getId(),cat_isrec.get(i).getCatname(),cat_isrec.get(i).getThumb()));
                if (i == 6) {
                    break;
                }
            }
            mList_HeadSort.add(new SeaAmoyListData.DataBean.Cat_isrecBean("","查看全部",R.mipmap.main_sort_all+""));
        } else {
            for (int i = 0; i < cat_isrec.size(); i++) {
                mList_HeadSort.add(new SeaAmoyListData.DataBean.Cat_isrecBean(cat_isrec.get(i).getId(),cat_isrec.get(i).getCatname(),cat_isrec.get(i).getThumb()));
            }
        }

        inflate = inflater.inflate(R.layout.head_search_sort_list_p, null, false);
        MyGridView nestlist_p = (MyGridView) inflate.findViewById(R.id.head_search_sort_list_nestlist_p);
        Adapt adapt = new Adapt(mList_HeadSort);
        nestlist_p.setAdapter(adapt);
        adapter.addHeaderView(inflate);
    }


    private void ReFreshData() {
        if (mRefreshLayout != null) {

            mRefreshLayout.setBackgroundColor(Color.TRANSPARENT);
            mRefreshLayout.setAutoRefreshDuration(400);
            mRefreshLayout.setRatioOfHeaderHeightToReach(1.5f);
            mRefreshLayout.addOnRefreshListener(new VRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                    if (networkConnected) {
                        mRefreshLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mRefreshLayout.refreshComplete();
                                page = 1;
                                GetSAmoyTC();
                                GetListData(page);
                            }
                        }, 1000);
                    } else {
                        ObjectUtils.toast(mcontext, "网络连接出现异常");
                    }
                }
            });
        }



    }

    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.click_resetnetwork_refresh:
                GetSAmoyTC();
                GetListData(page);
                break;

        }
    }


    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
        GetListData(page);
    }
    //获取分类
    private void GetSAmoyTC()
    {
        mList_HeadSort.clear();
        String address = ConstantsUrl.domain + ConstantsUrl.NATIONGOODSLIST ;
        HashMap<String,String> map = new HashMap<>();
        map.put("id",id);
        map.put("country_id",country_id);
        if (networkConnected) {

            HttpUtils.get(address,map, new SeaAmoyListDataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    //  ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(SeaAmoyListData response, int id) {
                    //ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);

                    if (response.getCode() == 0) {
                        cat_isrec.clear();
                        mList_HeadSort.clear();

                        if (response.getData().getCat_isrec() != null && !response.getData().getCat_isrec().equals("") &&response.getData().getCat_list().size() > 0) {
                            cat_isrec.addAll(response.getData().getCat_isrec());
                            initHeadSort();
                        }

                    }else {
                        noData.setVisibility(View.VISIBLE);
                        noDataTv.setVisibility(View.VISIBLE);
                        noDataTv.setText(response.getMsg());
                    }
                }
            });

        } else{

            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
            ObjectUtils.toast(mcontext, "连接连接出现异常");
        }
    }
    private void GetListData(final int page) {
        String address = ConstantsUrl.domain + ConstantsUrl.MAIN_LISTDATA + "?page="+page;
        HashMap<String,String> map = new HashMap<>();
        map.put("nid",id);
        map.put("country_id",country_id);
        if (networkConnected) {
            HttpUtils.get(address,map, new BrandGoodsListTCascadeCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {

                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(BrandGoodsListTCascadeData response, int id) {

                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);

                    if (response.getCode() == 0) {

                        if (response.getData().getList() == null && page == 1) {
                            noData.setVisibility(View.VISIBLE);
                            return;
                        }

                        smLayoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
                        mRecyclerView.setLayoutManager(smLayoutManager);
                        if (response.getData().getList() != null && response.getData().getList().size() > 0) {
                            if (page == 1) {
                                listdata.clear();
                                listdata.addAll(response.getData().getList());
                                adapter.setNewData(listdata);
                                mRecyclerView.setAdapter(adapter);
                            } else {
                                listdata.addAll(response.getData().getList());
                                adapter.addData(listdata);
                                mRecyclerView.setAdapter(adapter);
                                adapter.loadMoreComplete();
                            }
                        } else {
                            adapter.loadMoreEnd();
                        }
                    } else {
                        noData.setVisibility(View.VISIBLE);
                        noDataTv.setVisibility(View.VISIBLE);
                        noDataTv.setText(response.getMsg());
                    }
                }
            });
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(getActivity(), "网络连接出现异常");
            adapter.loadMoreFail();
        }
    }


    private class Adapt extends BaseAdapter {

        ArrayList<SeaAmoyListData.DataBean.Cat_isrecBean>   listdata;

        public Adapt(ArrayList<SeaAmoyListData.DataBean.Cat_isrecBean>  listdata) {
            this.listdata = listdata;
        }


        @Override
        public int getCount() {

            return listdata.size();


        }


        @Override
        public Object getItem(int position) {
            return null;
        }


        @Override
        public long getItemId(int position) {
            return 0;
        }


        @Override
        public View getView(final int pos, View convertView, ViewGroup parent) {
            View inflate_paystyle = LayoutInflater.from(mcontext).inflate(R.layout.list_pro_type_item, null);
            TextView typename = (TextView) inflate_paystyle.findViewById(R.id.typename);
            ImageView typeicon = (ImageView) inflate_paystyle.findViewById(R.id.typeicon);
            typename.setText(listdata.get(pos).getCatname());
            if (listdata.get(pos).getId().equals("")) {
                typeicon.setImageResource(Integer.parseInt(listdata.get(pos).getThumb()));
            } else {
                ObjectUtils.photo(mcontext, listdata.get(pos).getThumb(), typeicon);
            }
            inflate_paystyle.findViewById(R.id.typell).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mcontext,BaseObject.class);
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE,"海淘商品列表");
                    if(listdata.get(pos).getCatname().equals("查看全部"))
                    {
                        intent.putExtra("differ",0);
                    }
                    else
                    {
                        intent.putExtra("differ",pos+1);
                    }
                    intent.putExtra("nid",id);
                    startActivity(intent);
                }
            });
            return inflate_paystyle;
        }
    }
    private class AdaptList extends BaseMultiItemQuickAdapter<BrandGoodsListTCascadeData.DataBean.ListBean, BaseViewHolder> {
        private Context content;
        public AdaptList(Context context, ArrayList<BrandGoodsListTCascadeData.DataBean.ListBean> data, String type){
            super(data);
            this.content = context;
            addItemType(ConstantsUrl.THEMATICGOODSLISTItemTYPE, R.layout.item_grid_detail_like);
        }

        @Override
        protected void convert(BaseViewHolder holder,BrandGoodsListTCascadeData.DataBean.ListBean mainlistdata) {
            switch (holder.getItemViewType()) {
                case ConstantsUrl.THEMATICGOODSLISTItemTYPE:
                    ((TextView) holder.getView(R.id.item_grid_detail_like_number_before)).getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                    ObjectUtils.photo2(content, mainlistdata.getImg_src(),(ImageView) holder.getView(R.id.item_grid_detail_like_img));
                    holder.setText(R.id.item_grid_detail_like_title, mainlistdata.getName());
                    holder.setText(R.id.item_grid_detail_like_number_after, mainlistdata.getTeam_price());
                    holder.setText(R.id.item_grid_detail_like_number_before,mainlistdata.getPrice());
                    holder.setText(R.id.item_grid_detail_like_tuanshu, mainlistdata.getTeam_num());
                    break;
            }
        }
    }
}

